/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2018-2022. All rights reserved.
 */

package com.huawei.apig.sdk.demo;

import com.huawei.apig.sdk.util.Constant;
import com.huawei.apig.sdk.util.SSLCipherSuiteUtil;

import com.cloud.apigateway.sdk.utils.Client;
import com.cloud.apigateway.sdk.utils.Request;

import okhttp3.OkHttpClient;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WebSocketDemo {
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketDemo.class);

    public static void main(String[] args) throws Exception {
        // Create a new request.
        Request request = new Request();
        try {
            request.setKey("apigateway_sdk_demo_key");
            request.setSecret("apigateway_sdk_demo_secret");
            request.setMethod("GET");
            request.setUrl("your url");
        } catch (Exception e) {
            LOGGER.error("fail to contain request: {}", e.getMessage());
            throw e;
        }
        try {
            // Sign the request.
            okhttp3.Request signedRequest = Client.signOkhttp(request, Constant.SIGNATURE_ALGORITHM_SDK_HMAC_SHA256);
            // creat okhttpClient.
            OkHttpClient client = SSLCipherSuiteUtil.createOkHttpClient(Constant.INTERNATIONAL_PROTOCOL);

            WebSocketListener webSocketListener = new WebSocketListener() {
                @Override
                public void onMessage(WebSocket webSocket, String text) {
                    LOGGER.info("receive: " + text);
                }

                @Override
                public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                    LOGGER.info("fail   : " + t.getMessage());
                }
            };
            WebSocket webSocket = client.newWebSocket(signedRequest, webSocketListener);
            for (int i = 0; i < 10; i++) {
                String msg = "hello," + System.currentTimeMillis();
                LOGGER.info("send   : " + msg);
                webSocket.send(msg);
                Thread.sleep(50);
            }
            webSocket.close(1000, null);
            client.dispatcher().executorService().shutdown();
        } catch (Exception e) {
            LOGGER.error("fail to send the request: {}", e.getMessage());
            throw e;
        }
    }
}
